package com.yuyh.library.utils;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Joe on 2016/12/23.
 */

public class DownUtils {

    public static void downApk(OkHttpClient mOkHttpClient, String url, final String fileName, final Handler myHandler, Context context) {

        Request request = new Request.Builder().url(url).tag(context).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try{
                    myHandler.obtainMessage(1,"开始下载").sendToTarget();
                    saveFile(response,fileName,myHandler);
                    myHandler.obtainMessage(1,"下载完成").sendToTarget();
                }catch (IOException e){
                    myHandler.obtainMessage(-1,e.getLocalizedMessage()).sendToTarget();
                    e.printStackTrace();
                }
            }
        });
    }

    public static File saveFile(Response response,String fileName,final Handler myHandler) throws IOException{
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try{
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0;
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/download");
            if (!dir.exists()){
                dir.mkdirs();
            }
            File file = new File(dir,fileName);
            fos = new FileOutputStream(file);
            while ((len = is.read(buf))!=-1){
                sum+=len;
                fos.write(buf,0,len);
                final long finalSum = sum;
            //    DecimalFormat decimalFormat=new DecimalFormat("##0.00");
                float number = Math.round((finalSum*1.0f/total)*100);
           //     String p = decimalFormat.format(finalSum*1.0f/total);
                myHandler.obtainMessage(4,number).sendToTarget();

            }
            myHandler.obtainMessage(4,"1").sendToTarget();
            fos.flush();
            return file;
        }finally {
            try {
                if (is!=null){
                    is.close();
                }
            }catch(IOException e){
            }
            try{
                if(fos!=null){
                    fos.close();
                }
            }catch (IOException e){
            }
        }

    }
}
